package org.mj.im.common.lock.redisson;

import jakarta.annotation.Resource;

import org.mj.im.common.lock.DistributeLock;
import org.mj.im.common.lock.factory.DistributeLockFactory;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
// 基于 springboot的 ConditionalOnProperty 实现Spi机制
@ConditionalOnProperty(name = "distribute.lock.type",havingValue = "redisson")
public class RedissonLockFactory implements DistributeLockFactory {
    private final Logger logger = LoggerFactory.getLogger(RedissonLockFactory.class);

    @Resource
    private RedissonClient redissonClient;

    @Override
    public DistributeLock getDistributeLock(String key) {
        RLock lock = redissonClient.getLock(key);
        return new DistributeLock() {
            @Override
            public boolean tryLock(long waitTime, long timeout, TimeUnit unit) throws InterruptedException {
                boolean locked = lock.tryLock(waitTime, timeout, unit);
                logger.info("{} get lock status: {}", key, locked);
                return locked;
            }

            @Override
            public void lock(long leaseTime, TimeUnit unit) {
                lock.lock(leaseTime,unit);
            }

            @Override
            public void unlock() {
                if (lock.isLocked() && isHeldByCurrentThread()){
                    lock.unlock();
                }
            }

            @Override
            public boolean isLocked() {
                return lock.isLocked();
            }

            @Override
            public boolean isHeldByCurrentThread() {
                return lock.isHeldByCurrentThread();
            }

            @Override
            public boolean isHeldByThread(long threadId) {
                return lock.isHeldByThread(threadId);
            }
        };
    }
}
